<template>
  <div class="pie-chart" :style="chartStyle" ref="chartWrapper">
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'PieChart',
  props: {
    config: {
      type: Object,
      required: true,
      default: () => ({
        width: '100%',
        height: '300px',
        backgroundColor: '#093443',
        option: {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            show: true,
            orient: 'horizontal',
            top: '5%',
            left: 'center',
            textStyle: {
              color: '#fff',
              fontSize: 12
            }
          },
          series: [{
            name: '饼图数据',
            type: 'pie',
            radius: ['0%', '70%'],
            center: ['50%', '50%'],
            roseType: false,
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}: {d}%',
              color: '#fff'
            },
            data: [
              { name: '数据1', value: 335, itemStyle: { color: '#5470c6' } },
              { name: '数据2', value: 234, itemStyle: { color: '#91cc75' } },
              { name: '数据3', value: 158, itemStyle: { color: '#fac858' } }
            ]
          }]
        }
      })
    },
    apiObj: {
      type: Object,
      default: () => null
    }
  },
  data() {
    return {
      chart: null,
      refreshTimer: null
    }
  },
  computed: {
    chartStyle() {
      return {
        width: this.config.width,
        height: this.config.height,
        backgroundColor: this.config.backgroundColor
      }
    }
  },
  watch: {
    'config.option': {
      handler(newVal) {
        this.updateChart()
      },
      deep: true
    },
    'config.width'() {
      this.handleResize()
    },
    'config.height'() {
      this.handleResize()
    },
    apiObj: {
      handler(newVal) {
        if (newVal) {
          this.fetchData()
          this.setupAutoRefresh()
        } else {
          this.clearRefreshTimer()
        }
      },
      deep: true
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', this.handleResize)
    
    if (this.apiObj) {
      this.fetchData()
      this.setupAutoRefresh()
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    this.chart?.dispose()
    this.clearRefreshTimer()
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chartContainer)
      this.updateChart()
    },
    updateChart() {
      if (!this.chart) return
      this.chart.setOption(this.config.option, true)
    },
    handleResize() {
      this.$nextTick(() => {
        const wrapper = this.$refs.chartWrapper
        if (wrapper && this.chart) {
          this.chart.resize()
        }
      })
    },
    async fetchData() {
      if (!this.apiObj?.url) return
      
      try {
        const response = await fetch(this.apiObj.url, {
          method: this.apiObj.method || 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        })

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        const data = await response.json()
        
        // 获取数据
        const names = this.getValueByPath(data, this.apiObj.mapping.names) || []
        const values = this.getValueByPath(data, this.apiObj.mapping.values) || []

        // 更新图表配置
        const newOption = { ...this.config.option }
        newOption.series[0].data = names.map((name, index) => ({
          name,
          value: values[index] || 0,
          itemStyle: {
            color: this.getRandomColor()
          }
        }))

        this.$emit('update:config', {
          ...this.config,
          option: newOption
        })
      } catch (error) {
        console.error('获取远程数据失败:', error)
      }
    },
    setupAutoRefresh() {
      this.clearRefreshTimer()
      if (this.apiObj?.autoRefresh && this.apiObj.refreshInterval > 0) {
        this.refreshTimer = setInterval(() => {
          this.fetchData()
        }, this.apiObj.refreshInterval * 1000)
      }
    },
    clearRefreshTimer() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer)
        this.refreshTimer = null
      }
    },
    getValueByPath(obj, path) {
      return path.split('.').reduce((acc, part) => {
        return acc && acc[part]
      }, obj)
    },
    getRandomColor() {
      const colors = [
        '#5470c6', '#91cc75', '#fac858', '#ee6666',
        '#73c0de', '#3ba272', '#fc8452', '#9a60b4'
      ]
      return colors[Math.floor(Math.random() * colors.length)]
    }
  }
}
</script>

<style scoped>
.pie-chart {
  width: 100%;
  height: 100%;
  background: transparent !important;
  border: none !important;
}

.chart-container {
  width: 100%;
  height: 100%;
}

:deep(.echarts) {
  background: transparent !important;
  border: none !important;
}
</style> 